# Create your views here.
from uuid import uuid4
from django.core.files.storage import default_storage

from rest_framework.generics import ListAPIView

from app1.serializer import ShibieSerializer
from app1.models import ShiBieModels, ProcessingTask

from rest_framework.views import APIView
from rest_framework.response import Response
from app1.utils.helmet_shibie import HelmetShibie
from app1.tasks import process_video
import os

# import sys
# print(sys.path)

class ShiBie(APIView):
    def get(self,request):
        shuju = ShiBieModels.objects.order_by('-id').first()
        ser = ShibieSerializer(shuju)
        return Response(ser.data)
    # def post(self, request):
    #     file = request.FILES['image']
    #     # print((type(file.name)))
    #     shibie_duixiang=HelmetShibie(file)
    #     jieguo=shibie_duixiang.shibie()
    #     # print(jieguo)
    #     ser= ShibieSerializer(data=jieguo)
    #     ser.is_valid()
    #     if not ser.is_valid():
    #         print("验证错误:", ser.errors)  # 打印具体错误信息
    #         return Response(ser.errors, status=400)
    #     # print(ser.data)
    #     ser.save()
    #     return Response(ser.data)

    def post(self, request):
        file = request.FILES['image']
        print(type(file.name))
        if file.name.endswith(('.jpg', '.jpeg', '.png')):
            shibie_duixiang = HelmetShibie(file,task = None)
            result = shibie_duixiang.shibie()
            print(result)
            ser = ShibieSerializer(data=result)
            if ser.is_valid():
                ser.save()
            return Response(ser.data)
        task_id = str(uuid4())

        # 保存文件到临时位置
        file_path = default_storage.save(f'tmp/{task_id}{file.name}', file)

        # 创建任务记录
        task = ProcessingTask.objects.create(
            task_id=task_id,
            status='processing'
        )
        # 调用 Celery 异步任务
        # print(file_path)
        process_video.delay(task_id, file_path)


        return Response({
            'task_id': task_id,
            'status': 'processing',
            'progress': 0
        })

class TaskStatus(APIView):
    def get(self, request):
        task_id = request.query_params.get('task_id')
        try:
            task = ProcessingTask.objects.get(task_id=task_id)
            return Response({
                'status': task.status,
                'progress': task.progress,
                'result': task.result
            })
        except ProcessingTask.DoesNotExist:
            return Response({'error': 'Task not found'}, status=404)

class ShibieHistory(ListAPIView):
    queryset = ShiBieModels.objects.all()
    serializer_class = ShibieSerializer